package com.sso.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class StringUtil {

	public static String iso2UTF(String str) {
		if (str == null)
			return null;
		try {
			String temp_p = str;
			byte[] temp_t = temp_p.getBytes("ISO8859-1");
			String temp = new String(temp_t, "UTF-8");
			return temp;
		} catch (Exception e) {
		}
		return null;
	}

	public static String utf2ISO(String str) {
		if (str == null)
			return null;
		try {
			String temp_p = str;
			byte[] temp_t = temp_p.getBytes("UTF-8");
			String temp = new String(temp_t, "ISO8859-1");
			return temp;
		} catch (Exception e) {
		}
		return null;
	}

	public static String gbk2ISO(String str) {
		if (str == null)
			return null;
		try {
			String temp_p = str;
			byte[] temp_t = temp_p.getBytes("GBK");
			String temp = new String(temp_t, "ISO8859-1");
			return temp;
		} catch (Exception e) {
		}
		return null;
	}

	public static String toChartset(String str, String fromChartset,
			String toChartset) {
		if (str == null)
			return null;
		try {
			String temp_p = str;
			byte[] temp_t = temp_p.getBytes(fromChartset);
			String temp = new String(temp_t, toChartset);
			return temp;
		} catch (Exception e) {
		}
		return null;
	}

	public static String convert(String str) {
		String tmp;
		StringBuffer sb = new StringBuffer(10000);
		char c;
		int i, j;
		sb.setLength(0);
		for (i = 0; i < str.length(); i++) {
			c = str.charAt(i);
			if (c > 255) {
				sb.append("\\u");
				j = (c >>> 8);
				tmp = Integer.toHexString(j);
				if (tmp.length() == 1)
					sb.append("0");
				sb.append(tmp);
				j = (c & 0xFF);
				tmp = Integer.toHexString(j);
				if (tmp.length() == 1)
					sb.append("0");
				sb.append(tmp);
			} else {
				sb.append(c);
			}
		}
		return (new String(sb));
	}

	public static String list2Json(List list) {
		Map map = null;
		Map<String, Object> newMap = new HashMap<String, Object>();
		Iterator itera = null;
		StringBuffer strbuf = new StringBuffer("[");
		String key;
		String rst = null;
		for (int i = 0; list != null && i < list.size(); i++) {
			strbuf.append("{");
			map = (Map) list.get(i);
			itera = map.keySet().iterator();
			while (itera.hasNext()) {
				key = itera.next().toString();
				strbuf.append("\"" + key + "\":\"" + map.get(key) + "\",");
			}
			strbuf.deleteCharAt(strbuf.length()-1);
			if(i == list.size() -1) {
				strbuf.append("}");
			} else {
				strbuf.append("},");
			}
		}
		strbuf.append("]");
		return strbuf.toString();
	}
}
